package yxy.game.pm2.command.tower;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.TowerMessage;
import yxy.game.pm2.module.tower.RankTower;
import yxy.game.pm2.module.tower.TowerHandle;
import yxy.game.pm2.module.tower.TowerModule;

import java.util.Collection;

/** 修炼塔 修炼塔界面 */
@MessageType(proto = Command.TowerUI, classtype = TowerMessage.TowerUIRequest.class)
public class CMD_TowerUI extends Command<TowerMessage.TowerUIRequest> {

	@Override
	public void execute(MessageSource messageSource, TowerMessage.TowerUIRequest request) {
		String playerCode = messageSource.getTag();

		TowerMessage.TowerUIResponse.Builder response = TowerMessage.TowerUIResponse.newBuilder();

		TowerModule towerModule = TowerModule.get(playerCode);
		int cost = TowerHandle.buytimescost(towerModule.getBuytimes());

		response.setFloor(towerModule.getFloor());
		response.setTimes(towerModule.remainTimes());
		response.setBuytimes(towerModule.remainBuyTimes());
		response.setBuycost(cost);
		response.setQuick(towerModule.getAngers() != null);

		RankTower rankTower = RankTower.getRank(playerCode);

		Collection<RankEntry> top = rankTower.top(3);
		int rank = 0;
		for (RankEntry entry : top) {
			String pCode = entry.getKey();
			int floor = entry.getValue().intValue();
			PlayerBean playerBean = PlayerBean.get(pCode);

			TowerMessage.TopTower.Builder builder = TowerMessage.TopTower.newBuilder();
			builder.setRank(++rank);
			builder.setFloor(floor);
			builder.setName(playerBean.getName());
			response.addTop(builder);
		}

		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, TowerMessage.TowerUIResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}